# _*_ coding:utf-8 _*_
# @File  : account.py
# @Time  : 2021-12-07  10:18
# @Author: zizle
import datetime
from fastapi import APIRouter, Query

from db import FAConnection
from status import r_status
from tasks.investment import daily_profit

account_api = APIRouter()


# 获取各用户的投资账户情况
@account_api.get('/', summary='获取各用户的投资账户')
async def get_investment_account():
    db_conn = FAConnection(conn_name='admin获取投资账户')
    query_sql = 'SELECT a.id,a.create_time,a.user_id,a.account_name,a.account,a.initial_funds,a.funds,' \
                'a.bail,b.username,b.admin_name ' \
                'FROM user_invest_account AS a ' \
                'INNER JOIN user_user AS b ON a.user_id=b.id;'
    records = db_conn.query(query_sql)

    user_objs = {}
    # 找出所有的的用户ID
    for item in records:
        item['create_time'] = item['create_time'].strftime('%Y-%m-%d')
        if item['user_id'] not in user_objs.keys():
            user_objs[item['user_id']] = dict({'user_id': item['user_id'],
                                               'username': item['username'],
                                               'admin_name': item['admin_name'],
                                               'accounts': [item]})
        else:
            user_objs[item['user_id']]['accounts'].append(item)

    response_data = [user_objs[k] for k in user_objs.keys()]
    return {'code': r_status.SUCCESS, 'message': '获取用户投资号成功!', 'data': response_data}


# 统计当日的账号权益情况
@account_api.post('/', summary='计算账户的当日权益')
async def calculate_account(date: str = Query(None)):
    # if not '23:00:00' <= datetime.datetime.now().strftime('%H:%M:%S') <= '23:59:59':
    #     return {'code': r_status.FORBIDDEN, 'message': '非数据维护时段，不能操作!'}
    try:
        op_date = int(datetime.datetime.strptime(date, '%Y-%m-%d').timestamp())
    except ValueError:
        return {'code': r_status.VALIDATE_ERROR, 'message': '参数date格式错误!'}
    return daily_profit.generate_daily_profit(op_date)
